<?php

/**
 * Created by PhpStorm.
 * User: wx:wenyi2048
 * Date: 2022/3/29 0029
 * Time: 14:39
 */

namespace app\api\controller;


use app\common\model\mk\Users;
use app\common\service\AddressService;

class Address extends UserBase
{
    /**
     * 用户地址列表
     */
    public function datalist()
    {
        $this->param['def_id'] = $this->user['sms_address_id']; //默认地址放在第一位
        $aService = new AddressService($this->param);
        $result = $aService->dataList();
        return apiSuccess($result);
    }

    /**
     * 添加地址 返回插入id
     */
    public function add()
    {
        $validate = new \app\common\validate\mk\Address();

        if (!$validate->check($this->param)) {
            return apiError($validate->getError());
        }

        $aService = new AddressService($this->param);
        $id = $aService->add();
        return  apiSuccess($id);
    }

    /**
     * 编辑地址
     */
    public function edit()
    {
        $validate = new \app\common\validate\mk\Address();

        if (!$validate->check($this->param)) {
            return apiError($validate->getError());
        }

        $aService = new AddressService($this->param);

        if ($aService->edit()) {
            return apiSuccess();
        } else {
            return apiError('未修改数据');
        }
    }

    public function delete()
    {
        if (empty($this->param['id'])) return apiError('请指定删除地址');
        $aService = new AddressService($this->param);
        if ($aService->delete()) {
            return apiSuccess();
        } else {
            return apiError('未修改数据');
        }
    }

    /**
     * 设置默认地址,地址id
     */
    public function edit_def()
    {
        if (empty($this->param['id'])) return apiError('参数错误');
        $user = Users::find($this->userId);
        $user->sms_address_id = $this->param['id'];
        if ($user->save()) return  apiSuccess();
        else return apiError();
    }
}
